﻿using IOP.OpenType;
using IOP.OpenType.Tables;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// OTF文件解码器
    /// </summary>
    public partial class OTFDecoder
    {
        /// <summary>
        /// 读取CFF表
        /// </summary>
        /// <returns></returns>
        public async Task<CFFTable> ReadCFFTable()
        {
            if (OffsetTable == null) await ReadOffsetTable();
            TableEntry entry = GetEntry(TableNames.CFF);
            if (_Tables.TryGetValue(entry.Tag, out Table cff))
            {
                CFFTable cffTable = cff as CFFTable;
                return cffTable;
            }
            await _SemaphoreSlim.WaitAsync();
            try
            {
                if (_Tables.TryGetValue(entry.Tag, out cff))
                {
                    CFFTable cffTable = cff as CFFTable;
                    return cffTable;
                }
                using FileStream stream = new FileStream(FileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                CFFLoader loader = new CFFLoader();
                var table = await loader.Load(stream, entry);
                _Tables.AddOrUpdate(entry.Tag, table, (key, value) => value);
                return table;
            }
            finally
            {
                _SemaphoreSlim.Release();
            }
        }
    }
}
